package org.zlb.netty.client.udp;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.util.CharsetUtil;

public class ChinesProverClient {

    private int port;
    
    public ChinesProverClient(int port) {
        this.port = port;
    }
    
    public void run() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
             .channel(NioDatagramChannel.class)
             .handler(new ChinesProverClientHandler())
             .option(ChannelOption.SO_BROADCAST, true);
    
            Channel channel = b.bind(0).sync().channel();
            
            ByteBuf data = Unpooled.copiedBuffer("中华成语故事大全", CharsetUtil.UTF_8);
            channel.writeAndFlush(new DatagramPacket(data, new InetSocketAddress("255.255.255.255", port)));
            
            if (!channel.closeFuture().await(15000)){
                System.out.println("timeout");
            }
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        ChinesProverClient client = new ChinesProverClient(8088);
        client.run();
    }
}
